package com.resou.reader.tinder;

import android.util.Log;

import com.resou.reader.ReSouApplication;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.data.Injection;
import com.resou.reader.data.tinder.TinderRepository;
import com.resou.reader.data.tinder.tinder.SlideBean;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.ToastUtil;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.resou.reader.commom.Constant.APP;

public class SwipePresenter extends ResouBasePresenter<ISwipeView> {
    public static final String FAVORITES_SIZE = "favorites_size";
    public static final String PAGE = "page";
    public static final String FAVORITES_IDS = "favorites_ids";
    private int START_PAGE = 1;
    private boolean isRequestInProgress = false;
    private static final String TAG = "SwipePresenter";
    private final TinderRepository mRepository;
    private List<SlideBean> mSlideBeans;

    public SwipePresenter(ISwipeView view) {
        super(view);
        mRepository = Injection.provideTinderRepository(ReSouApplication.getRSApplication());
    }

    public void loadFavoritesCount() {
        mSlideBeans = mRepository.loadLocalCartCount();
        mView.showFavoritesCount(String.valueOf(mSlideBeans.size()));
    }

    public int getBookIds() {
        return mSlideBeans.size();
    }

    /**
     * 获取初始列表
     */
    public void getSwipeList(final String token) {
        //请求正在进行中取消本次请求
        if (isRequestInProgress) return;
        //在我们启动网络请求时设置为true
        isRequestInProgress = true;
        if (mView == null) {
            return;
        }
        mView.showProgress();

        addCompositeDisposable(
                mRepository.getSlideList(START_PAGE, token, APP)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        //此处注释代码处理presenter生命周期，
                        // activity或fragment不在屏幕上将不执行subscribe方法导致视图不能更新
                        .subscribe(slideBeanResult -> {
                            if (slideBeanResult.getCode() == 0) {
                                List<SlideBean> data = slideBeanResult.getData();
                                START_PAGE = START_PAGE + 1;
                                isRequestInProgress = false;
                                if (data.size() == 0) {
                                    getSwipeList(token);
                                } else {
                                    mView.addSwipeList(data);
                                    mView.showContent();
                                    mView.setError(null);
                                }
                            } else {
                                ToastUtil.makeLongToast(slideBeanResult.getMsg());
                            }
                        }, throwable -> {
                            Log.d(TAG, "getSwipeList: " + throwable.getMessage());
                            ErrorUtils.showError(throwable);
                            mView.showError(throwable);
                            isRequestInProgress = false;
                        }));
    }

    /**
     * 获取下一页
     */
    public void getNextSwipeList(String token) {
        //请求正在进行中取消本次请求
        if (isRequestInProgress) return;
        //在我们启动网络请求时设置为true
        isRequestInProgress = true;
//        mToken
        addCompositeDisposable(
                mRepository.getSlideList(START_PAGE, token, APP)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(slideBeanResultList -> {
                            if (slideBeanResultList.getCode() == 0) {
                                List<SlideBean> data = slideBeanResultList.getData();
                                mView.addSwipeList(data);
                                START_PAGE = START_PAGE + 1;
                                mView.showContent();
                                isRequestInProgress = false;
                                mView.setError(null);
                            }
                        }, throwable -> {
                            DLog.e(TAG, "getMainRankList error! mes=" + throwable.getMessage());
//                                ErrorUtils.showError(throwable);
                            mView.setError(throwable);
                            isRequestInProgress = false;
                        }));
    }

    /**
     * 此方法应该是告诉服务器不再推荐此书
     */
    public void noLongerRecommended() {

    }

    /**
     * 获取收藏夹书本的数量
     */
    public void getCartCount(String token) {
        addCompositeDisposable(
                mRepository.getCartCount(token)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(result -> {
                            String count = result.getData();
                            //显示界面右上角的收藏数量
                            mView.showFavoritesCount(count);
                        }, ErrorUtils::showError));
    }

    /**
     * 添加到收藏夹
     *
     * @param slideBean slideBean
     */
    public void addToShoppingCart(SlideBean slideBean, final String token) {
        if (mSlideBeans.size() >= 20) {
            ToastUtil.makeShortToast("收藏夹已超出上限，请删除后添加");
            mView.onUndoClick();
            return;
        }
        if (mSlideBeans.contains(slideBean)) {
            ToastUtil.makeShortToast("此书已存在");
            return;
        }
        mSlideBeans.add(slideBean);
        addCompositeDisposable(mRepository.addToShoppingCart(slideBean, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe()
        );

        mView.showFavoritesCount(String.valueOf(mSlideBeans.size()));
        //添加到本地和远程收藏夹

    }

    /**
     * 上传待提交列表
     * @param token
     */
    public void uploadLastPendingSubmissionSlideBean(final String token) {
        addCompositeDisposable(mRepository.loadPendingSubmitSlideBean()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(slideBeans -> {
                    for (int i = 0; i < slideBeans.size(); i++) {
                        mRepository.addToShoppingCart(slideBeans.get(i), token);
                    }
                }, throwable -> Log.d(TAG, "accept: " + throwable.getMessage()))
        );
    }
}
